
T4B.GpxBuilder = Class.create({
  build:function(builder,points){
 	  builder.append('<?xml version="1.0"?> \n');
	  builder.append('<gpx version="1.1" creator="Tracks4Bikers.com" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">\n');
	  builder.append('<metadata> <name>Track</name> <author><name>Tracks4Bikers.com</name></author> </metadata>\n');
	  builder.append('<trk>\n');
	  builder.append('<name>TODO</name>\n');
	  builder.append(' <trkseg>\n');
	  for (var i=0;i<points.length;i++){
      builder.append('  <trkpt lat="'+points[i].lat+'" lon="'+points[i].lng+'">\n');
      builder.append('    <ele>'+points[i].elev+'</ele>\n');
      builder.append('  </trkpt>\n');
	  }
	  builder.append(' </trkseg>\n');
	  builder.append('</trk>\n');
	  builder.append("</gpx>\n");
  }
});

T4B.TCXParser = Class.create({
  parse:function(manager,xmlDoc){
    activities=xmlDoc.getElementsByTagName("Activity");
		for (cta=0;cta<activities.length;cta++){
		  var totalSecs=0, totalDist=0;
		  activity=activities[cta];
		  key=activity.getElementsByTagName('Id')[0].childNodes[0].nodeValue;
      if (manager.isKeyLoaded(key)) continue;

		  var lapsElem=activity.getElementsByTagName('Lap');
		  for (var j=0;j<lapsElem.length;j++){
        totalSecs+=parseInt(lapsElem[j].getElementsByTagName('TotalTimeSeconds')[0].childNodes[0].nodeValue);
        totalDist+=parseInt(lapsElem[j].getElementsByTagName('DistanceMeters')[0].childNodes[0].nodeValue);
		  };

		  console.log("Distance: "+totalDist);
		  console.log("Seconds: "+totalSecs);
      var avgSpeed=0;
      if (totalSecs>0) avgSpeed=(totalDist/totalSecs*3.6).toFixed(3);

		  x=activity.getElementsByTagName("Trackpoint");
		  var lats=[], lngs=[], alts=[], dists=[], secs=[];
		  var date=new Date();
		  isodate=x[0].getElementsByTagName('Time')[0].childNodes[0].nodeValue;
		  var startDate=new Date();
		  startDate.setISO8601(isodate);
		  console.log("x.length="+x.length);
		  for (i=0;i<x.length;i++) {
			  if (x[i].getElementsByTagName('Position').length==0) continue;
			  var index=lats.length;
			  lats[index]=parseFloat(x[i].getElementsByTagName('LatitudeDegrees')[0].childNodes[0].nodeValue);
			  lngs[index]=parseFloat(x[i].getElementsByTagName('LongitudeDegrees')[0].childNodes[0].nodeValue);
			  isodate=x[i].getElementsByTagName('Time')[0].childNodes[0].nodeValue;
			  date.setISO8601(isodate);
			  secs[index]=(date-startDate)/1000;
			  alts[index]=parseFloat(x[i].getElementsByTagName('AltitudeMeters')[0].childNodes[0].nodeValue);
			  dists[index]=parseFloat(x[i].getElementsByTagName('DistanceMeters')[0].childNodes[0].nodeValue);
		  };
		  var data={lats: lats, lngs: lngs, secs: secs, alts: alts, dists:dists };
      var track={key:key, date:key.substring(0,10), dist:totalDist, secs:totalSecs, avgspeed:avgSpeed, data:data};

      manager.storeTrack(track);
    }
  }
});


/*
 Gmap panel
 */

T4B.GMap = Class.create({
  initialize:function(id){
	  this.map = new GMap2($(id));
	  this.map.addControl(new GSmallZoomControl3D());
	  this.map.addControl(new GMapTypeControl());
  },

  clear:function(){
    this.map.clearOverlays();
  },

  trackChanged:function(track){
    this.points=[];
    var bounds=new GLatLngBounds();
	  for (var i=0;i<track.points.length;i++){
      var p=new GLatLng(track.points[i].lat, track.points[i].lng);
      this.points[this.points.length]=p;
      bounds.extend(p);
	  };
	  var level=this.map.getBoundsZoomLevel(bounds);
	  this.map.setCenter(bounds.getCenter(),level);
	  var poly=new GPolyline(this.points);
	  this.map.addOverlay(poly);
  }
});


T4B.TrackPanel = Class.create({
  initialize:function(id){
	  this.id=id;
  },

  clear:function(){
    Element.update(this.id+"_name",'');
    Element.update(this.id+"_date",'');
    Element.update(this.id+"_distance",'');
    Element.update(this.id+"_secs",'');
    Element.update(this.id+"_avgSpeed",'');
    Element.update(this.id+"_description",'');
  },

  trackChanged:function(track){
    Element.update(this.id+"_name",track.name);
    Element.update(this.id+"_date",track.date);
    Element.update(this.id+"_distance",(track.distance/1000).toFixed(3));
    Element.update(this.id+"_secs",Date.secs2Date(track.secs));
    Element.update(this.id+"_avgSpeed",track.avgSpeed);
    Element.update(this.id+"_description",track.description);
  }
});

T4B.TrackEditor = Class.create({
  initialize:function(id){
	  this.id=id;
    var me=this;
    $(this.id+"_form").onsubmit=function(){return me.onSubmit()};
    this.buttonEl=$(this.id+"_button");
    if (this.buttonEl!=null) this.buttonEl.onclick=function(){Element.show(me.id)};
    this.clear();
  },

  clear:function(){
    $(this.id+"_form").reset();
    this.buttonEl.disabled=true;
  },

  trackChanged:function(track){
    this.track=track;
    $(this.id+"_name").value=track.name;
    $(this.id+"_description").value=track.description;
    this.buttonEl.disabled=false;
  },

  onSubmit:function(){
    Element.hide(this.id);
    if (this.track==null) return false;
    this.track.name=$(this.id+"_name").value;
    this.track.description=$(this.id+"_description").value;
    this.manager.updateTrack(this.track);
    return false;
  }
});


T4B.TracksList = Class.create({
  initialize:function(id){
    this.id=id;
  },
  listTracksChanged:function(tracks){
    var s="<table><tr><th>Date</th><th>Distance</th><th>Name</th></tr>";
	  for (var i=0;i< tracks.length;i++){
 //     s+="<button style='width:280px' onclick='javascript:app.showTrack("+tracks[i].id+")'>"+tracks[i].name+"</button><br/>";
     s+="<tr><td>"+tracks[i].date+"</td>";
     s+="<td>"+(tracks[i].distance/1000).toFixed(3)+"</td>";
     s+="<td><a href='#' onclick='return app.showTrack("+tracks[i].id+")'>"+tracks[i].name+"</a></td></tr>";
	  };
    s+="</table>";
	  Element.update(this.id,s);
  }
});

T4B.TPList = Class.create({
  initialize:function(id){
    this.id=id;
    this.selectEl=$(id+"_select");
    var me=this;
    this.selectEl.onchange=function(){me.selChange()};
    $(this.id+"_loadAll").onclick=function(){me.loadAll()};
    $(this.id+"_form").onsubmit=function(){ return me.onSubmit()};
    this.isNotIE=!Prototype.Browser.IE;
    this.loadAllPoints=false;
  },
  clear:function(){
    var len=this.selectEl.length;
    for (var i=len-1;i>=0;i--)
      this.selectEl.remove(i);
    this.selectEl.length=0;
    this.loadAllPoints=false;
  },
  trackChanged:function(track){
    var d1=new Date().getTime();
    var points=track.points;
    this.points=points;
    for (var i=0;i<points.length;i++){
     if (i==100 && !this.loadAllPoints) break;
     var text=this.setTextOption(i);
     this.appendOption(i,text);
    };
    var d2=new Date().getTime();
  },
  setTextOption:function(i){
    var points=this.points;
    var label=points[i].label|| '' ;
    var text=i+" | "+(points[i].dist/1000).toFixed(3)+" | " + points[i].elev.toFixed(0) +" | " + points[i].secs+" | " +  label;
    return text;
  },
  appendOption:function(index,text){
    var elOptNew = document.createElement('option');
    elOptNew.value = index;
    elOptNew.text=text;
    this.points[index].elOpt=elOptNew;
    if (this.isNotIE)
      this.selectEl.add(elOptNew, null);
    else
      this.selectEl.add(elOptNew); // IE only
  },
  selChange:function(){
    var selIndex=this.selectEl.selectedIndex;
    if (selIndex<0) return;
    $(this.id+'_elev').value=this.points[selIndex].elev;
    $(this.id+'_label').value=this.points[selIndex].label || '';
    var iconN=this.points[selIndex].icon || 0;
    $(this.id+'_icon').selectedIndex=iconN;
    //$('elev').disabled=out;
    //$('label').disabled=out;
    //$('icon').disabled=out;
    //$('updatePoint').disabled=out;
    //editor.prof.highlightPoint(selIndex);
    //if (isMap) editor.setMarker(editor.pts[selIndex].llp);
  },
  loadAll:function(){
    if (this.points==null) return;
    this.clear();
    this.loadAllPoints=true;
    var t={points: this.points};
    this.trackChanged(t);
  },
  onSubmit:function(){
    var selIndex=this.selectEl.selectedIndex;
    if (selIndex<0) return;
    if (this.points==null) return false;
    this.points[selIndex].label=$(this.id+"_label").value;
    this.points[selIndex].icon=$(this.id+"_icon").selectedIndex;
    this.points[selIndex].elev=parseFloat($(this.id+"_elev").value);
    this.points[selIndex].elOpt.text=this.setTextOption(selIndex);
    return false;
  }
});

T4B.TracksBar = Class.create({
  initialize:function(id){
    this.id=id;
    this.ct=0;
    this.tracks=[];
    var me=this;
    $(this.id+"_prev").onclick=function(){me.move(-1)};
    $(this.id+"_next").onclick=function(){me.move(+1)};
    $(this.id+"_prev").disabled=true;
    $(this.id+"_next").disabled=true;
  },
  listTracksChanged:function(tracks){
    this.tracks=tracks;
    if (this.ct>=tracks.length) this.ct=0;
    this.move(0);
  },
  clear:function(){
  },
  trackChanged:function(track){
    for (var i=0;i<this.tracks.length;i++){
      if (this.tracks[i].id==track.id){
        this.ct=i;
        this.move(0);
        return;
      }
    }
  },
  move:function(inc){
    this.ct+=inc;
    $(this.id+"_prev").disabled=(this.ct<=0);
    $(this.id+"_next").disabled=(this.ct>=this.tracks.length-1);
    if (!this.tracks[this.ct]) return;
    if (inc!=0) this.manager.showTrack(this.tracks[this.ct].id);
    var total=0;
    if (this.tracks) total=this.tracks.length;
    Element.update(this.id+"_status","Track "+this.ct + " / "+total);
  }
});


T4B.FlotrProfile = Class.create({
  initialize:function(id){
    this.id=id;
    //TODO flotr:mousemove, flotr:select events
    $(this.id).observe('flotr:click', function(event){
      var position = event.memo[0];
      console.log(position.x);
    });
  },

  clear:function(){
  },

  trackChanged:function(track){
    var points=track.points;
    var d1 = [];
	  for(var i = 0; i < points.length; i ++){
			d1.push([points[i].dist/1000, points[i].elev]);
    };
    var f= Flotr.draw($(this.id), [{data: d1, lines: {show: true, fill: true}}] );
  }
});
